package com.qfedu.fmmall.service.impl;

import com.qfedu.fmmall.dao.ShoppingCartMapper;
import com.qfedu.fmmall.entity.ShoppingCart;
import com.qfedu.fmmall.entity.ShoppingCartVo;
import com.qfedu.fmmall.service.ShoppingCartService;
import com.qfedu.fmmall.vo.ResultStatus;
import com.qfedu.fmmall.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    private SimpleDateFormat sdf = new SimpleDateFormat();

    @Override
    public ResultVo addShoppingCart(ShoppingCart cart) {
        cart.setCartTime(sdf.format(new Date()));
        int i = shoppingCartMapper.insert(cart);
        if(i>0){
            return new ResultVo(ResultStatus.OK,"success",null);
        }else{
            return new ResultVo(ResultStatus.NO,"fail",null);
        }
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    public ResultVo listShoppingCartByUserId(int userId) {
        List<ShoppingCartVo> shoppingCartVos = shoppingCartMapper.selectShopCartByUserId(userId);
        ResultVo resultVo = new ResultVo(ResultStatus.OK, "success", shoppingCartVos);
        return  resultVo;
    }

    @Override
    public ResultVo updateCartNum(int cartId, int num) {
        int i = shoppingCartMapper.updateCartNumById(cartId, num);
        if(i>0){
            return new ResultVo(ResultStatus.OK,"update success",null);
        }else{
            return new ResultVo(ResultStatus.NO,"update fail",null);
        }
    }

    @Override
    public ResultVo listShopCartByCIds(String CIds) {
        String[] split = CIds.split(",");
        List<Integer> arrayList = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            arrayList.add(Integer.parseInt(split[i]));
        }
        List<ShoppingCartVo> list = shoppingCartMapper.selectShopCartByCIds(arrayList);
        return new ResultVo(ResultStatus.OK,"success",list);
    }
}
